<template>
  <div class="suggestion-detail">
    <div class="status">
      <img :src="statusUrl" />
    </div>
    <div class="suggestion-detail-wrapper flex-column">
      <div class="title mt-15 mb-15 pb-15">{{ title }}</div>
      <div class="flex-center" style="height: 100%" v-if="loading">
        <a-spin size="large" tip="Loading..." />
      </div>
      <div
        ref="dialogueRef"
        class="dialogue pl-10 pr-10"
        v-else
        @mouseenter="showScrollBar"
        @mouseleave="hiddenScrollBar"
      >
        <div class="common-content initiate-content">
          <div
            v-for="(item, index) of initiateList"
            :class="[
              'common-item initiate-item',
              { 'self-item': item.selfFlag },
            ]"
            :key="index"
          >
            <div class="initiate flex">
              <div class="avatar flex-center">
                {{ item.user_name?.slice(-2) }}
              </div>
              <div class="right-wrap ml-15">
                <div class="name-time flex">
                  <div class="username">{{ item.user_name }}</div>
                  <div class="create-time ml-10">
                    {{ item.create_time }}
                  </div>
                </div>
                <div class="content mt-10" v-html="item.content"></div>
              </div>
            </div>
          </div>
        </div>

        <a-divider style="color: #a2dbcc; font-size: 14px; margin-top: 35px"
          >看看大家都怎么说的~</a-divider
        >

        <div class="common-content reply-content flex-column">
          <div
            v-for="(item, index) of replyList"
            :class="[
              'common-item reply-item',
              { 'self-reply': item.selfFlag, 'other-reply': !item.selfFlag },
            ]"
            :key="index"
          >
            <template v-if="item.selfFlag">
              <div class="self-reply-info flex">
                <div class="left-wrap flex-column">
                  <div class="name-time flex">
                    <div class="create-time">
                      {{ item.create_time }}
                    </div>
                    <div class="username ml-10">{{ item.user_name }}</div>
                  </div>
                  <div class="content mt-10" v-html="item.content"></div>
                </div>

                <div class="avatar flex-center ml-15">
                  {{ item.user_name?.slice(-2) }}
                </div>
              </div>
            </template>

            <template v-else>
              <div class="other-reply-info flex">
                <div class="avatar flex-center">
                  {{ item.user_name?.slice(-2) }}
                </div>
                <div class="right-wrap ml-15">
                  <div class="name-time flex">
                    <a-tag color="green" v-if="Number(item.user_id) === 2"
                      >开发者</a-tag
                    >
                    <div class="username">{{ item.user_name }}</div>
                    <div class="create-time ml-10">
                      {{ item.create_time }}
                    </div>
                  </div>
                  <div class="content mt-10" v-html="item.content"></div>
                </div>
              </div>
            </template>
          </div>
        </div>
      </div>
      <div class="reply">
        <div class="wrapper flex-column">
          <textarea
            type="text"
            rows="6"
            v-model="answerValue"
            @keydown="handleKeydown"
          ></textarea>
          <button class="button" @click="reply">回复</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { useRoute } from "vue-router";

import {
  getSuggestionDetail,
  getSuggestionReplyList,
  replySuggestion,
} from "../../api/suggestion";
import { getLocal } from "../../utils/storage";
import resolved from "../../assets/images/statusImage/resolved.png";
import unread from "../../assets/images/statusImage/unread.png";
import rejected from "../../assets/images/statusImage/rejected.png";
import processing from "../../assets/images/statusImage/processing.png";

let imgReflect = {
  0: unread,
  1: processing,
  2: resolved,
  3: rejected,
};

let userId = getLocal("plan_user_id");
const route = useRoute();
const id = ref(null);

let title = ref(null);
let statusUrl = ref(null);
const loading = ref(false);
let initiateList = ref([]);
// 创建者的id 用于之后推送消息
let createUserId = ref(null);
let replyList = ref([]);
function getSuggestionItem() {
  loading.value = true;
  return new Promise((resolve) => {
    getSuggestionDetail({
      id: id.value,
    }).then((res) => {
      if (res.code === 0) {
        statusUrl.value = imgReflect[res.data.status];
        createUserId.value = res.data.user_id;
        res.data.selfFlag = res.data.user_id === Number(userId);
        title.value = res.data.title;
        let index = res.data.content.indexOf("<img");
        // -(index + 1) -> 抽象渗漏
        if (~index) {
          let imgClosedIndex = res.data.content.indexOf("/>", index);
          let beforeImgContent = res.data.content.slice(0, index);
          let imgContent = res.data.content.slice(index, imgClosedIndex + 2);
          let restContent = res.data.content.slice(imgClosedIndex + 2);
          initiateList.value = [
            {
              ...res.data,
              content: beforeImgContent,
            },
            {
              ...res.data,
              content: imgContent,
            },
            {
              ...res.data,
              content: restContent,
            },
          ];
        } else {
          initiateList.value.push(res.data);
        }
        resolve();
      }
    });
  });
}
function getReplyList() {
  return new Promise((resolve) => {
    getSuggestionReplyList({
      suggestionId: id.value,
    }).then((res) => {
      loading.value = false;
      if (res.code === 0) {
        res.data.forEach((item) => {
          item.selfFlag = Number(userId) === item.user_id;
        });
        replyList.value = res.data;
      }
      resolve();
    });
  });
}

onMounted(() => {
  id.value = route.query.id;
  getSuggestionItem().then(() => getReplyList());
});

const dialogueRef = ref(null);
function showScrollBar(e) {
  dialogueRef.value.classList.add("scroll-bar-class");
}
function hiddenScrollBar(e) {
  dialogueRef.value.classList.remove("scroll-bar-class");
}
const answerValue = ref(null);
function handleKeydown(e) {
  if (e.keyCode === 13) {
    e.preventDefault();
    reply();
  }
}

function reply() {
  if (!answerValue.value) return;
  replySuggestion({
    username: getLocal("plan_user_name"),
    content: answerValue.value,
    suggestionId: id.value,
    createUserId: createUserId.value,
    title: title.value,
  }).then((res) => {
    if (res.code === 0) {
      answerValue.value = "";
      getReplyList().then(() => {
        dialogueRef.value.scrollTop = dialogueRef.value.scrollHeight;
      });
    }
  });
}
</script>

<style scoped lang="less">
.suggestion-detail {
  height: 100%;
  font-size: 16px;
  padding: 32px;
  background-image: linear-gradient(to right, #faedf1 0%, #fce6ed 100%);
  position: relative;

  .status {
    position: absolute;
    top: 36px;
    height: 36px;
  }

  &-wrapper {
    height: 100%;
    overflow: hidden;
    padding-bottom: 32px;
    border-radius: 24px;
    background-color: #fff;
    width: 60%;
    margin: 0 auto;

    .title {
      padding-left: 32px;
      font-size: 18px;
      font-weight: bold;
      border-bottom: 1px solid @border-color;
    }

    .dialogue {
      flex: 1;
      overflow-y: auto;
      box-sizing: border-box;

      &::-webkit-scrollbar {
        width: 0;
      }

      // 滚动条的轨道的两端按钮，允许通过点击微调小方块的位置。
      &::-webkit-scrollbar-button {
        display: none;
      }
      // 滚动条的轨道（里面装有Thumb）
      &::-webkit-scrollbar-track {
        background: transparent;
      }
      // 滚动条的轨道（里面装有Thumb）
      &::-webkit-scrollbar-track-piece {
        background-color: transparent;
      }
      // 滚动条里面的小方块，能向上向下移动（或往左往右移动，取决于是垂直滚动条还是水平滚动条）
      &::-webkit-scrollbar-thumb {
        background: transparent !important;
        cursor: pointer;
        border-radius: 12px;
      }
      // 边角，即两个滚动条的交汇处
      &::-webkit-scrollbar-corner {
        display: none;
      }
      // 两个滚动条的交汇处上用于通过拖动调整元素大小的小控件
      &::-webkit-resizer {
        display: none;
      }

      .common-content {
        .common-item {
          margin-top: 16px;

          .avatar {
            background-image: linear-gradient(
              to right bottom,
              rgba(162, 219, 204, 1),
              rgba(162, 219, 204, 0.2)
            );
            // background-color: #a2dbcc;
            color: #fff;
            width: 66px;
            height: 66px;
            border-radius: 50%;
          }

          .name-time {
            font-size: 14px;
            color: @shallow-text-color;
          }

          .content {
            width: max-content;
            background-color: #f6f8fa;
            padding: 16px 8px;
            border-radius: 8px;
            letter-spacing: 0.5px;
          }

          &:first-child {
            margin-top: 0;
          }
        }

        .self-item {
          .content {
            background-color: #95ec69;
          }
        }

        .reply-item {
          margin-top: 16px !important;

          &.self-reply {
            align-self: flex-end;

            .name-time {
              align-self: flex-end;
            }

            .content {
              background-color: #95ec69;
              align-self: flex-end;
            }
          }

          &.other-reply {
            .name-time {
              align-items: baseline;
            }
          }
        }
      }

      &.scroll-bar-class {
        // 滚动条样式

        &::-webkit-scrollbar {
          width: 8px;
        }

        // 滚动条的轨道的两端按钮，允许通过点击微调小方块的位置。
        &::-webkit-scrollbar-button {
          display: none;
        }
        // 滚动条的轨道（里面装有Thumb）
        &::-webkit-scrollbar-track {
          background: transparent;
        }
        // 滚动条的轨道（里面装有Thumb）
        &::-webkit-scrollbar-track-piece {
          background-color: transparent;
        }
        // 滚动条里面的小方块，能向上向下移动（或往左往右移动，取决于是垂直滚动条还是水平滚动条）
        &::-webkit-scrollbar-thumb {
          background: #e7e6e6 !important;
          cursor: pointer;
          border-radius: 12px;
        }
        // 边角，即两个滚动条的交汇处
        &::-webkit-scrollbar-corner {
          display: none;
        }
        // 两个滚动条的交汇处上用于通过拖动调整元素大小的小控件
        &::-webkit-resizer {
          display: none;
        }
      }
    }

    .reply {
      border-top: 1px solid @border-color;
      width: 100%;
      margin-top: 32px;
      padding: 8px 16px 0;
      box-sizing: border-box;

      .wrapper {
        border-radius: 0 8px 0 0;
        background-color: #f6f8fa;
        position: relative;
        padding-bottom: 64px;
      }

      textarea {
        flex: 1;
        letter-spacing: 1px;
        text-indent: 10px;
        outline: none;
        border: 1px solid transparent;
        border-radius: 0 8px 0 0;
        font-size: 18px;
        padding-top: 5px;
        background-color: transparent;
      }

      .button {
        cursor: pointer;
        z-index: 66;
        position: absolute;
        bottom: 16px;
        right: 16px;
        white-space: nowrap;
        margin-top: 16px;
        width: 80px;
        padding: 8px;
        align-self: flex-end;
        outline: none;
        border: 1px solid #69dbbd;
        background-color: #69dbbd;
        color: #fff;
        border-radius: 4px;

        &:hover {
          opacity: 0.7;
        }
      }
    }
  }
}
</style>
